/**
 * Ajax请求
 * @param string url
 * @param object params
 * @param GET|POST type
 * @returns XMLHttp
 */
function toAjax(url,data,type){
    $.ajaxSetup({
        headers: {
            'X-XSRF-TOKEN': $.cookie('XSRF-TOKEN')
        }
    });
    var dom = $('<div></div>');
    var index = layer.load(1, {
        shade: [0.1,'#fff'] //0.1透明度的白色背景
    });
    var ajax = $.ajax({
        url:url,
        data:data,
        type:type,
        success:function (data, textStatus) {
            if(data.code == 1){
                try{
                    dom.trigger('hxop.ajax-success',data.data, textStatus);
                }catch(e){
                    console.error(e);
                }
            }else{
                parent.layer.alert('失败!失败原因:' + data.message);
                try{
                    dom.trigger('hxop.ajax-failed',data.data,textStatus)
                }catch(e){
                    console.error(e);
                }
            }
            layer.close(index);
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            parent.layer.alert('失败!错误:' + textStatus);
            try{
                dom.trigger('hxop.ajax-error',XMLHttpRequest, textStatus,errorThrown);
            }catch(e){
                console.error(e);
            }
            layer.close(index);
        },
        complete:function(XMLHttpRequest, textStatus){
            layer.close(index);
            try{
                dom.trigger('hxop.ajax-complete',XMLHttpRequest, textStatus);
            }catch(e){
                console.error(e);
            }
        }
    });
    return {
        abort:ajax.abort,
        on:function(){
            dom.on.apply(dom,arguments);
            return this;
        },
        off:function(){
            dom.off.apply(dom,arguments);
            return this;
        },
        one:function(){
            dom.one.apply(dom,arguments);
            return this;
        }
    };
}

var uniqueId = (function(){
    var count = 0;
    return function(){
        return count++;
    }
})();

/**
 * 解析url
 *@param {string} url 完整的URL地址
 *@returns {object} 自定义的对象
 *@description 用法示例：var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
 myURL.file='index.html'

 myURL.hash= 'top'

 myURL.host= 'abc.com'

 myURL.query= '?id=255&m=hello'

 myURL.params= Object = { id: 255, m: hello }

 myURL.path= '/dir/index.html'

 myURL.segments= Array = ['dir', 'index.html']

 myURL.port= '8080'

 myURL.protocol= 'http'

 myURL.source= 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'

 */
function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: function(){
            var arr = [];
            $.each(this.params,function(k,v){
                arr.push(k + '=' + v);
            });
            return arr.join('&');
        },
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/'),
        addParam:function(k,v){
            this.params[k] = v;
        },
        pack:function(){
            var url = '';
            if(this.host){
                url += this.protocol + '://' + this.host;
                if(this.port){
                    url += ':' + this.port;
                }
            }
            if(this.path){
                url += this.path;
            }
            var paramstr = this.query();
            if(paramstr.length > 0){
                url += '?' + paramstr;
            }
            return url;
        }
    };
}
var pager = {
    goPage:function(el,page){
        var url = parseURL($(el).parent().data('path'));
        url.addParam('page',page);
        location.href = url.pack();
    },
};

function go_page(url,params){
    var p = [];
    if(params){
        $.each(params,function(k,v){
            p.push(k + '=' + v);
        });
        if(p.length > 0){
            url += '?' + p.join('&');
        }
    }
    location.href = url;
}

function setDateRange(start,end){
    $(start).on('change',initDate).datepicker({
        startView: 1,
        todayBtn: "linked",
        keyboardNavigation: false,
        forceParse: false,
        autoclose: true,
        format: "yyyy-mm-dd"
    });
    $(end).on('change',initDate).datepicker({
        startView: 1,
        todayBtn: "linked",
        keyboardNavigation: false,
        forceParse: false,
        autoclose: true,
        format: "yyyy-mm-dd"
    });

    var start = $(start);
    var end = $(end);
    var pStart = start.data('datepicker');
    var pEnd = end.data('datepicker');

    function initDate(){
        var sDate = pStart.getDate();
        var eDate = pEnd.getDate();
        pStart.setEndDate(eDate);
        pEnd.setStartDate(sDate);
    }
}

function mkmap(src,column){
    var o = {};
    $.each(src,function(k,v){
        if(column === undefined && typeof(v) != 'object'){
            o[v] = v;
        }else{
            o[v[column]] = v;
        }
    });
    return o;
}

function flip(arr){
    var o = {};
    $.each(arr,function(k,v){
        o[v] = k;
    });
    return o;
}

function obj_values(o){
    var arr = [];
    $.each(o,function(k,v){
        arr.push(v);
    });
    return arr;
}

function groupby(src,column){
    var o = {};
    $.each(src,function(k,v){
        var key = v[column];
        if(key in o){
            o[key].push(v);
        }else{
            o[key] = [v];
        }
    });
    return o;
}

function cp(src,columns){
    var o = {};
    $.each(columns,function(k,v){
        o[v] = src[v];
    });
    return o;
}
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt)
{ //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
Date.Format = function (timestamp, fmt) {
    var date = new Date();
    date.setTime(timestamp);
    return date.Format(fmt);
};


var Validator = {
    is_phone:function(v){
        return /^(13|14|15|17|18)[0-9]{9}$/.test(v);
    },
    is_int:function(v){
        return /^\d+$/.test(v);
    },
    is_object:function(v){
        console.log('is_object',v,typeof(v) == 'object');
        return typeof(v) == 'object';
    },
    is_array:function(v){
        console.log('is_array',v,this.is_object(v));
        return this.is_object(v) && v instanceof Array;
    },
    arr_not_empty:function(v){
        console.log('arr_not_empty',v,this.is_array(v));
        return this.is_array(v) && v.length > 0;
    },
    is_empty:function(v){
        console.log('is_empty',v,!this.arr_not_empty(v),!this.is_int(v) && !v);
        return (this.is_array(v) && v.length == 0) || (!this.is_int(v) && !v);
    }
};

var JqgridTable = (function(){
    var op = {
        data: [],
        datatype: "local",
        height: 250,
        autowidth: true,
        shrinkToFit: true,
        rowNum: 14,
        rowList: [10, 20, 50],
        colNames: [],
        colModel: [],
        pager: "",
        viewrecords: true,
        caption: "筛选结果",
        hidegrid: false
    }
    var JqgridTable = function(el,options,url,method){
        var me = this;
        this._grid = null;
        this._el = el;
        this._options = options;
        this._url = url;
        this._method = method;
        this._dom = $(this._el);
        $(document).ready(function(){
            me._show([]);
        });
    }

    JqgridTable.prototype = {
        getData:function(p,cl){
            var me = this;
            toAjax(this._url, p, this._method)
                .on('hxop.ajax-success', function (evt, data) {
                    var list = cl?cl(data.list):data.list;
                    me._show(list);
                    me._dom.trigger('hxop.jqgrid-show',data);
                });
            return this;
        },
        show:function(list){
            this._show(list);
        },
        _show:function(list){
            var me = this;
            if(this._grid){
                var mygrid = this._grid[0];
                this._grid.jqGrid('clearGridData');
                mygrid.addJSONData(list);
            }else{
                var op = this._op();
                op.list = list;
                this._grid = $(this._el).jqGrid(op);
                this._grid.setGridWidth(1000);
                //$(window).on('resize',function(){
                //    me._setWidth();
                //});
            }
        },
        _setWidth:function(){
            var w = this._grid.parents('.jqGrid_wrapper').width();
            this._grid.setGridWidth(w);
        },
        _op:function(){
            var rt = {};
            var _op = this._options;
            $.each(op,function(k,v){
                if(k in _op){
                    rt[k] = _op[k];
                }else{
                    rt[k] = v;
                }
            })
            return rt;
        },
        on:function(){
            this._dom.on.apply(this._dom,arguments);
            return this;
        },
        off:function(){
            this._dom.off.apply(this._dom,arguments);
            return this;
        },
        one:function(){
            this._dom.one.apply(this._dom,arguments);
            return this;
        },
        dom:function(){
            return $(this._el);
        }
    };
    return JqgridTable;
})();

var uniqueId = (function(){
    var count = 0;
    return function (){
        return count++;
    }
})();

function getPackagesDetails(items){


    function getLine(name,data){
        return '<tr>' +
            '<td>' + name + '</td>' +
            '<td>' + data.name + '</td>' +
            '<td>' + data.value + '</td>' +
            '<td>' + data.min_investment + '</td>' +
            '<td>' + data.duration + '</td>' +
            '<td>' + data.expire_date + '</td>' +
            '<td>' + data.effective_duration + '</td>' +
            '</tr>';
    }
    var s = '';
    $.each(items.cash_voucher_list, function (k, v) {
        s += getLine('现金券',v);
    });
    $.each(items.rate_increment_voucher_list, function (k, v) {
        s += getLine('加息券',v);
    });
    $.each(items.red_packet_list, function (k, v) {
        s += getLine('红包',v);
    });
    return s;
}